<!--
* description: 计划订单管理
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamicButtons="tableButtons"
      :dynamicComponents="tableComponents"
      :dynamicApiConfig="apiConfig"
      :dynamicTableCols="tableCols"
      :dynamicFormFields="formField"
      :dynamicUnFormFields="unFormField"
      :dynamicIsShowSelect="true"
      :dynamicIsColumnDrop="true"
      :callbackObj="callbackObj"
    >
      <template slot="CONFIRM_QTY" slot-scope="scope">
        <el-input
          v-model="scope.row.CONFIRM_QTY"
          type="text"
          @input="numChange(scope)"
          style="width:100%;"
          class="tableTemplate"
          maxlength="10"
          v-if="scope.row.PLAN_STATUS === '0'"
        />
        <span v-else>{{ scope.row.CONFIRM_QTY }}</span>
      </template>
      <template slot="CHANGE_REASON" slot-scope="scope">
        <el-input
          v-model="scope.row.CHANGE_REASON"
          type="text"
          style="width:100%;"
          class="tableTemplate"
          maxlength="100"
          v-if="scope.row.PLAN_STATUS === '0'"
        />
        <span v-else>{{ scope.row.CHANGE_REASON }}</span>
      </template>
    </one-table-template>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import { wmsApis } from "@/api/wms/allocation/api";
import OneTableTemplate from "@/components/wms/templates/oneTable";
import request from "@/utils/request";
import store from "@/store";
export default {
  name: "planOrderManage",
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],
  components: {
    OneTableTemplate
  },
  watch: {
    $route(val) {
      if (
        this.formField.pageId !== "" &&
        this.$route.query.pageId !== undefined &&
        this.$route.query.pageId !== this.formField.pageId
      ) {
        this.formField.pageId = this.$route.query.pageId;
        this.formField.pageName = this.$route.query.pageName;
        this.queryTable();
      }
    }
  },
  created() {
    if (this.$route.query != null) {
      // 判断传入query参数，初始化数据
      if (this.$route.query.pageId != null && this.$route.query.pageId !== "") {
        this.formField.pageId = this.$route.query.pageId;
        this.formField.pageName = this.$route.query.pageName;
      }
    }
  },
  mounted() {
    this.querySelect();
  },
  data() {
    return {
     partNoBefore:'', //备件编号  处理前不加逗号的
      Before:'', //供应商编号  处理前不加逗号的

      // 网格查询API配置对象
      apiConfig: wmsApis.queryPlanOrder,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          clickEvent: () => this.queryBtn(),
          name: "search",
          position: "right",
          text: "查询" //"查询"
        },
        {
          compKey: "btnKey2",
          type: "",
          size: "small",
          clickEvent: () => this.export(),
          name: "export",
          position: "left",
          text: "导出" //"导出"
        },
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          name: "reset",
          position: "right",
          clickEvent: () => this.reset(),
          text: "重置"
        },
        {
          compKey: "btnKey4",
          type: "",
          size: "small",
          name: "saveSubmit",
          position: "left",
          clickEvent: () => this.save(),
          text: "保存"
        },
        {
          compKey: "btnKey5",
          type: "",
          size: "small",
          name: "newOrder",
          position: "left",
          clickEvent: () => this.transformation(),
          text: "转订单"
        },
        {
          compKey: "btnKey6",
          type: "",
          size: "small",
          name: "importTemplateDownload",
          position: "left",
          clickEvent: () => this.downloadTemplate(),
          text: "模板下载" //"模板下载"
        },
        {
          compKey: "btnKey7",
          text: "导入",
          category: "ve",
          codeField: "fileChannel",
          position: "upload",
          isMust: true
        }
      ],
      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: "compKey1",
          labelName: "计划单号",
          codeField: "PLAN_ORDER_CODE",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          options: []
        },
        {
          compKey: "compKey10",
          labelName: "要货仓库",
          codeField: "WAREHOUSE_ID",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          options: []
        },
        {
          compKey: "compKey12",
          labelName: "发货仓库",
          codeField: "SRC_WAREHOUSE_ID",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          options: []
        },
        {
          compKey: "compKey2",
          labelName: "计划日期",
          codeField: "PLAN_DATE_NEW_START",
          component: () => import("@/components/wms/datePicker/andtDatePicker"),
          type: "date",
          isMust: true
        },
        {
          compKey: "compKey3",
          labelName: "计划类型",
          codeField: "PLAN_TYPE",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          options: []
        },
        {
          compKey: "compKey4",
          labelName: "状态",
          codeField: "PLAN_STATUS",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          options: []
        },
          {
          compKey: "compKey6",
          labelName: "备件名称",
          codeField: "PART_NAME",
          component: () => import("@/components/wms/commonInput"),
          type: "inputText",
          isMust: true
        },
          {
          compKey: "compKey8",
          labelName: "ABC分类",
          codeField: "ABC_TYPE",
          component: () => import("@/components/wms/dropdownList/dropdownList"),
          type: "dropdownList",
          isMust: true,
          options: [
            {
              label: "A类",
              value: "A"
            },
            {
              label: "B类",
              value: "B"
            },
            {
              label: "C类",
              value: "C"
            }
          ]
        },
        // {
        //   compKey: "compKey5",
        //   labelName: "备件编码",
        //   codeField: "PART_NO",
        //   component: () => import("@/components/wms/commonInput"),
        //   type: "inputText",
        //   isMust: true
        // },
          {
          compKey: "compKey5",
          labelName: "备件编码",
          codeField: "PART_NOS", //['0','9]
          component: () => import("@/components/org/commonInput/textareaInput"),
          // type: "inputText",
          isMust: true,
        },
      
        // {
        //   compKey: "compKey7",
        //   labelName: "供应商编号",
        //   codeField: "SUPPLIER_CODE",
        //   component: () => import("@/components/wms/commonInput"),
        //   type: "inputText",
        //   isMust: true
        // },
         {
          compKey: "compKey7",
          labelName: "供应商编号",
          codeField: "SUPPLIER_CODES", //['0','9]
          component: () => import("@/components/org/commonInput/textareaInput"),
          // type: "inputText",
          isMust: true,
        },
      
      ],
      // 动态生成网格列
      tableCols: [
        {
          prop: "PLAN_ORDER_CODE",
          label: "计划单号",
          align: "center",
          width: "120"
        },
        {
          prop: "PLAN_DATE_NEW",
          label: "计划日期",
          align: "center",
          width: "100"
        },
        {
          prop: "PLAN_TYPE_NAME",
          label: "计划类型",
          align: "center",
          width: "100"
        },
        {
          prop: "WAREHOUSE_NAME",
          label: "要货仓库",
          align: "center",
          width: "100"
        },
        {
          prop: "SRC_WAREHOUSE_NAME",
          label: "发货仓库",
          align: "center",
          width: "100"
        },
        {
          prop: "PART_NO",
          label: "备件编码",
          align: "center",
          width: "100"
        },
        {
          prop: "PART_NAME",
          label: "备件名称",
          align: "center",
          width: "100"
        },
        {
          prop: "SUPPLIER_CODE",
          label: "供应商编号",
          align: "center",
          width: "100"
        },
           {
          prop: "PARTNER_SHORT_NAME",
          label: "供应商简称",
          align: "center",
          width: "100"
        },
        {
          prop: "PLAN_QTY",
          label: "计划数量",
          align: "center",
          width: "100"
        },
        {
          prop: "CONFIRM_QTY",
          label: "修正数量",
          align: "center",
          width: "100",
          isSlot: true,
          overflow: false
        },
        {
          prop: "CHANGE_REASON",
          label: "调整原因",
          align: "center",
          width: "100",
          isSlot: true,
          overflow: false
        },
        {
          prop: "SAFETY_STORE",
          label: "安全库存",
          align: "center",
          width: "100"
        },
        {
          prop: "ACCOUNT_QTY",
          label: "可用库存",
          align: "center",
          width: "100"
        },
        {
          prop: "INTRANSIT_QTY",
          label: "采购在途",
          align: "center",
          width: "100"
        },
        {
          prop: "LACK_QTY",
          label: "欠拨数量",
          align: "center",
          width: "100"
        },
        {
          prop: "SNP_IN",
          label: "采购SNP",
          align: "center",
          width: "100"
        },
        {
          prop: "ORDER_PERIOD",
          label: "订货周期",
          align: "center",
          width: "100"
        },
        {
          prop: "ARRIVAL_PERIOD",
          label: "到货周期",
          align: "center",
          width: "100"
        },
        {
          prop: "AMC",
          label: "月均需求数量",
          align: "center",
          width: "100"
        },
        {
          prop: "MONTH_QTY",
          label: "统计月基数",
          align: "center",
          width: "100"
        },
        {
          prop: "SAFETY_FACTOR",
          label: "安全库存调整系数",
          align: "center",
          width: "100"
        },
        {
          prop: "TARGET_SERVICE_RATE",
          label: "目标服务率",
          align: "center",
          width: "100"
        },
        {
          prop: "SALE_FLUCTATE_DIFF",
          label: "销售波动偏差",
          align: "center",
          width: "100"
        },
        {
          prop: "ARRIVE_FLUCTATE_DIFF",
          label: "到货波动偏差",
          align: "center",
          width: "100"
        }
      ],
      //表单查询数据
      formField: {
        WAREHOUSE_ID: "",
        PLAN_ORDER_CODE: "",
        PLAN_DATE_NEW_START: "",
        PART_NOS: "",
        PART_NAME: "",
        SUPPLIER_CODES: "",
        PLAN_TYPE: "",
        PLAN_STATUS: "",
        ABC_TYPE: "",
        SRC_WAREHOUSE_ID: "",
        PARTNER_SHORT_NAME:""
      },
      unFormField: {},
      // 回调函数
      callbackObj: {
        //  当选择项发生变化时会触发该事件
        onCheckSelectChange: selection => {
          this.checkTableList = selection;
        },
           onBeforeQuery: queryObj => {
           queryObj.variables.PART_NOS = queryObj.variables.PART_NOS.trim()
            .split("\n")
            .toString();
              queryObj.variables.SUPPLIER_CODES = queryObj.variables.SUPPLIER_CODES.trim()
            .split("\n")
            .toString();
        },
        
      },
      // 选中的表格数据
      checkTableList: []
    };
  },
  methods: {
    transformation() {
      if (this.formField.PLAN_ORDER_CODE) {
        this.$confirm("确定要转订单吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
          .then(() => {
            request({
              url: "/mp/wm/vl/warehouse/ppplanorder/planOrderToPurchase.do",
              method: "post",
              data: {
                PLAN_ORDER_CODE: this.formField.PLAN_ORDER_CODE
              }
            }).then(res => {
              if (res.result === "1") {
                this.queryTable();
                this.$message({
                  message: "转订单成功",
                  type: "success"
                });
              } else {
                this.$message({
                  message: res.debugMsg ? res.debugMsg : res.msg,
                  type: "warn"
                });
              }
            });
          })
          .catch(err => {
            console.info(err);
          });
      } else {
        this.$message({
          message: "请选择计划单号再转订单"
        });
      }
    },
    save() {
      if (this.checkTableList.length > 0) {
        let flag = false;
        this.checkTableList.forEach(item => {
          if (!item.CONFIRM_QTY) {
            flag = true;
          }
        });
        if (flag) {
          this.$message({
            message: "选中的数据有修改数量未输入"
          });
          return;
        }
        this.$confirm("确定要保存吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
          .then(() => {
            request({
              url: "/mp/wm/vl/warehouse/ppplanorder/updatePlanConfirmQty.do",
              method: "post",
              data: {
                ConfirmQty: this.checkTableList
              }
            }).then(res => {
              if (res.result === "1") {
                this.queryTable();
                this.$message({
                  message: "保存成功",
                  type: "success"
                });
              } else {
                this.$message({
                  message: res.debugMsg ? res.debugMsg : res.msg,
                  type: "warn"
                });
              }
            });
          })
          .catch(err => {
            console.info(err);
          });
      } else {
        this.$message({
          message: "请选择一条数据"
        });
      }
    },
    getSelectable(row, index, ref) {
      if (row.PLAN_STATUS === "0") {
        return true;
      } else {
        return false;
      }
    },
    numChange(scope) {
      if (scope.row.CONFIRM_QTY < 1) {
        scope.row.CONFIRM_QTY = "";
      }
      scope.row.CONFIRM_QTY = (scope.row.CONFIRM_QTY + "").replace(
        /[^\d]/g,
        ""
      );
      if (scope.row.CONFIRM_QTY) {
        this.$refs.multipleTable.$refs.multipleTable.toggleRowSelection(
          scope.row,
          true
        );
      }
    },
    queryBtn() {
      if (!this.formField.PLAN_ORDER_CODE) {
        this.$message({
          message: "请选择计划单号再查询",
          uration: 2000
        });
        return;
      }
      this.queryTable();
    },
    querySelect() {
      // 计划单号
      request({
        url: "/mp/wm/vl/warehouse/ppplanorder/queryPlanOrderCode.do",
        method: "post",
        data: {}
      }).then(res => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map(item => {
            this.tableComponents[0].options.push({
              label: item.PLAN_ORDER_CODE,
              value: item.PLAN_ORDER_CODE
            });
          });
        }
      });
      // 要货仓库
      request({
        url: "/mp/wm/vl/basedata/warehouseuser/queryUserByWHBox.do",
        method: "post",
        data: {
          IS_ENABLE: "1"
        }
      }).then(res => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map(item => {
            this.tableComponents[1].options.push({
              label: item.WAREHOUSE_NAME,
              value: item.WAREHOUSE_ID
            });
          });
        }
      });
      // 发货仓库
      request({
        url: "/mp/wm/vl/warehouse/ppplanorder/querySrcWarehouse.do",
        method: "post",
        data: {
          IS_ENABLE: "1"
        }
      }).then(res => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map(item => {
            this.tableComponents[2].options.push({
              label: item.SRC_WAREHOUSE_NAME,
              value: item.SRC_WAREHOUSE_ID
            });
          });
        }
      });
      // 计划类型
      request({
        url: "/mp/wm/vl/warehouse/ppplanorder/queryPlanType.do",
        method: "post",
        data: {}
      }).then(res => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map(item => {
            this.tableComponents[4].options.push({
              label: item.PLAN_TYPE_NAME,
              value: item.PLAN_TYPE
            });
          });
        }
      });
      // 状态
      request({
        url: "/mp/wm/vl/warehouse/ppplanorder/queryPlanStatus.do",
        method: "post",
        data: {}
      }).then(res => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map(item => {
            this.tableComponents[4].options.push({
              label: item.PLAN_STATUS_NAME,
              value: item.PLAN_STATUS
            });
          });
        }
      });
      // abc
      request({
        url: "/mp/wm/vl/warehouse/ppplanorder/queryPlanStatus.do",
        method: "post",
        data: {}
      }).then(res => {
        if (res.listRow && res.listRow.length > 0) {
          res.listRow.map(item => {
            this.tableComponents[5].options.push({
              label: item.PLAN_STATUS_NAME,
              value: item.PLAN_STATUS
            });
          });
        }
      });
    },
    export() {
        this.partNoBefore = this.formField.PART_NOS;
     
      this.formField.PART_NOS = this.formField.PART_NOS.trim().split("\n").toString();
      this.Before = this.formField.SUPPLIER_CODES;
     
      this.formField.SUPPLIER_CODES = this.formField.SUPPLIER_CODES.trim().split("\n").toString();

      if (!this.formField.PLAN_ORDER_CODE) {
        this.$message({
          message: "请选择计划单号再查询",
          uration: 2000
        });
        return;
      }
      const exportLoading = this.$loading({
        lock: true,
        text: "正在导出...",
        // spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        fullscreen: true
      });
      request({
        url: "/mp/wm/vl/warehouse/ppplanorder/exportPlanOrder.do",
        method: "post",
        headers: {
          "Cache-Control": "no-cache, no-store,max-age=0, must-revalidate",
          Pragma: "no-cache",
          Expires: "0",
          "Content-Type": "application/json;charset=UTF-8"
        },
        responseType: "blob",
        data: this.formField
      })
        .then(response => {
          exportLoading.close();
          let blob = new Blob([response], { type: "application/vnd.ms-excel" }); // 这里表示xmlx类型
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href;
          downloadElement.download = "计划订单管理导出.xls"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        })
           .then(response =>{
        this.formField.PART_NOS = this.partNoBefore;
        })  
         .then(response =>{
        this.formField.SUPPLIER_CODES = this.Before;
        })
        .catch(err => {
          exportLoading.close();
          console.log(err);
        });
    },
    downloadTemplate() {
      let downloadElement = document.createElement("a");
      let href = "/wms/fileTemplate/计划订单管理模板.xls"; // 创建下载的链接
      downloadElement.href = href;
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handFileListChange(file, fileList) {},
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: "文件大小不能超过50M",
          type: "warning"
        });
        return false;
      }
      let fileType = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (fileType != "xls" && fileType != "xlsx") {
        this.$message({
          message: "只能导入后缀为xls,xlsx的文件！",
          type: "warning"
        });
        return false;
      }
      return true;
    },
    handleChange(param) {

    // this.formField.PART_NOS=this.formField.PART_NOS.trim().split("\n").toString();
    // this.formField.SUPPLIER_CODES = this.formField.SUPPLIER_CODES.trim().split("\n").toString();

      const loading = this.$loading({
        lock: true,
        text: "导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      const that = this;
      const url = "/mp/wm/vl/warehouse/ppplanorder/importExcelToPlanOrder.do";
      that
        .$requestUpload(url, param)
        .then(response => {
          loading.close();
          if (response.result === "1") {
            this.$message({
              message: "导入成功",
              type: "success"
            });
            if (this.formField.PLAN_ORDER_CODE) {
              that.queryTable();
            }
          } else {
            this.$message({
              message: response.msg,
              type: "warning"
            });
          }
        })
        .catch(err => {});
    }
  }
};
</script>
<style type="text/css" lang="scss" scoped>
/deep/ .tableTemplate .el-input__inner {
  border: none;
}
</style>
